import axios from 'axios'
import qs from "qs"
import { ElMessage } from 'element-plus'

var base = window.API_SERVER || "";
// 创建axios实例
const axiosInstance = axios.create({
  baseURL: base,
  headers:{
     "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"
  }
})
// application/x-www-form-urlencoded
axiosInstance.interceptors.request.use( config => {
  return config
}, error => {
  Promise.reject(error)
})

// respone拦截器
axiosInstance.interceptors.response.use(
  response => {
   
    if(response.data){
      if(response.data.code === 200 || response.data.code === 0){
          return Promise.resolve(response.data.data);
      }else{
        if (response.data.constructor === ArrayBuffer) {
          return Promise.resolve(response.data)
        } else {
          var msg = response.data.msg || "服务器错误";
          ElMessage.error(msg);
          return Promise.reject({code:500,msg:msg,step:1})
        }
      }
    }else{
        ElMessage.error("服务器错误");
      return Promise.reject({code:500,msg:"服务器错误",step:2})
    }
  },
  error => {
    ElMessage.error(error.message ||  "网络错误");
    return Promise.reject(error)
  });



export const get = (url,params,config)=>{
  return axiosInstance.get(url,{params,...config});
}

export const post = (url,params,config)=>{
  return axiosInstance.post(url,qs.stringify(params), config);
}


